# from __future__ import absolute_import, unicode_literals
import json
import base64

from celery import shared_task
import time

from user.models import UserProfile
from utils.myredis import r
from utils.baiduapi import BaiDuApi
from utils.download import download_image
from django.utils import timezone  # 添加导入
from django.db import connection

# @shared_task
# def bdcardmes():
#     # 从redis list中获取10条信息
#     # 调用百度api接口
#     # 将结果存入redis
#     blist = r.list_lrange('baiduurllist', 0, 10)
#     if blist:
#         for i in blist:
#             picurl = i.decode()
#             # 调用百度api接口
#             mes = BaiDuApi.idcard_ocr(picurl)
#             # 存入redis {"name":"zs","code":"234234"}
#             r.set_str(picurl, json.dumps(mes))
#             r.list_del('baiduurllist', picurl)
#
#     print("调用百度api接口")


# tasks.py
@shared_task(bind=True, max_retries=3)
def process_realname_task(self):
    try:
        # 原子性地获取任务
        task_json = r.list_pop('realname:queue')
        if not task_json:
            return

        task_data = json.loads(task_json)

        # 下载图片，得到二进制内容
        front_img_bytes = download_image(task_data['front_url'])
        back_img_bytes = download_image(task_data['back_url'])

        # 转为base64字符串
        front_img_base64 = base64.b64encode(front_img_bytes).decode()
        back_img_base64 = base64.b64encode(back_img_bytes).decode()

        # 调用OCR接口
        ocr = BaiDuApi()
        front_result = ocr.idcard_ocr(front_img_base64, 'front')
        back_result = ocr.idcard_ocr(back_img_base64, 'back')

        print('front_result:', front_result)
        print("打印图片路径:")
        print('front_url:', task_data['front_url'])
        print('back_url:', task_data['back_url'])

        # 验证信息
        words_result = front_result.get('words_result')
        if not words_result:
            # 记录日志或处理异常
            raise KeyError('words_result')
        ocr_name = words_result['姓名']['words']
        ocr_id = words_result['公民身份号码']['words']
        is_valid = (ocr_name == task_data['name']) and (ocr_id == task_data['id_number'])

        # 更新数据库
        if is_valid:
            UserProfile.objects.filter(user_id=task_data['user_id']).update(
                is_realname=True,
                realname=task_data['name'],
                id_number=task_data['id_number'],
            )
            # 强制断开 ORM 连接，确保后续查询拿到最新数据
            connection.close()

        # 存储结果
        result_key = f"realname:result:{task_data['user_id']}"
        r.setex_str(result_key, 86400, json.dumps({  # 缓存24小时
            'status': 'success' if is_valid else 'failed',
            'ocr_data': {
                'front': front_result,
                'back': back_result
            },
            'verified': is_valid,
            'verified_at': str(timezone.now()) if is_valid else None
        }))

    except Exception as e:
        # 任务失败，重新放回队列
        r.list_rush('realname:queue', task_json)
        self.retry(exc=e, countdown=60)